#!/usr/bin/env ruby
# coding: utf-8

#srand(Time.now.to_i)

#実行中のスクリプトのディレクトリをロードパスに追加
#http://vividtone.seesaa.net/article/90206702.html
$:.push(File.expand_path(File.dirname(__FILE__)))

load 'config.rb',true

require 'rubygems'
require 'TwitterClass'
#require 'TwitterClass2'
require 'DatabaseClass'
require 'TalkClass'
#require 'oauth-patch' #Ruby1.9以上の人
#require 'yaml'
require 'json'

#########
def order(twitter,order='',user='',m_id='')
	parse = order.split(/[:]/)
	case parse[0]
	when 'follow'
		twitter.follow(user)
	when 'unfollow'
		twitter.unfollow(user)
	when 'retweet'
		twitter.retweet(m_id)
	when 'favorite'
		twitter.favorite(m_id)
	when 'setImg'
		twitter.change_profile_image(parse[1]) if(parse[1]!=nil)
	end
end
#########

logdata = DatabaseClass.new
twitter = TwitterClass.new($config[:CONSUMER_KEY],$config[:CONSUMER_SECRET],$config[:ACCESS_TOKEN],$config[:ACCESS_TOKEN_SECRET])
talk = TalkClass.new

data = logdata.get_dataset

puts "[#{Time.now.strftime("%Y/%m/%d %H:%M:%S")}] ==== Start Bot  ===="

#POST規制解除チェケ
now_error_count = data['post_error'].to_i
if (data['status'] == "post_error")
	message = talk.pub_command("#{data['error_start']}ぐらいから<NowTime>までPOST規制でした。")
	puts message
	if (twitter.update(message)) then
		logdata.update_dataset("status","normal")
		logdata.update_dataset("error_start","0")
		logdata.update_dataset("post_error","0")
		now_error_count = 0
	else
		now_error_count += 1
		if (now_error_count > 3) then
			logdata.update_dataset("status","post_error")
			logdata.update_dataset("error_start",Time.now.strftime("%Y/%m/%d %H:%M:%S"))
			logdata.update_dataset("post_error","#{now_error_count}")
			puts "[#{Time.now.strftime("%Y/%m/%d %H:%M:%S")}] POST ERROR count #{now_error_count}"
			exit
		end
	end
end

#twitter.update('こんにちわ')

#ツィートに関する処理
count=0
puts "---- get timeline ----"
since=data['latestTW']
##ツィートを取得
if(since!='0') then
	statuses = twitter.get_timeline("since_id=#{since}")
else 
	statuses = twitter.get_timeline()
end

##対応を考える
latestTW=''
begin
	if (statuses!=nil) then
		#JSON.parse(statuses.body).reverse_each do |status|
		JSON.parse(statuses.body).each do |status| #reverse_eachが使えないとき
			next if(status==nil)
			latestTW=status['id'] if(latestTW=='') #eachなので一番最初のが最新のtweet
			count += 1
  		twitter.dump_status_data(status) if(status!=nil)
			logdata.recvTW(status['id'],status['created_at'],status['user']['screen_name'],status['text'])
			result = talk.parse('TW',status['user']['screen_name'],status['text'])
			if (result['message']!=nil and result['message']!='') then
				#命令に対応
				order(twitter,result['order'],status['user']['screen_name'],status['id']) if(result['order']!='')

				tweet = "@#{result['to']} #{result['message']}"
				puts "\t -- update #{tweet}"
				if (twitter.update(tweet)) then
					#投稿ログに記録
					logdata.sendTW(status['user']['screen_name'],status['text'])
					now_error_count=0
				else
					now_error_count+=1
				end
			end
		end
	end
rescue JSON::ParserError
	time = Time.now.strftime("%Y/%m/%d %H:%M:%S")
	puts "#{time}\t[Error:TL] cannot parse json"
end
logdata.latest_TW(latestTW)  if(latestTW!=nil and latestTW!='')
puts "---- All #{count} stasuses  ----\n\n"

#ダイレクトメッセージに関する処理
count=0
puts "---- get direct messages ----"
since=data['latestDM']
##ダイレクトメッセージを取得
if(since!='0') then
	messages = twitter.get_directmessage("since_id=#{since}")
else 
	messages = twitter.get_directmessage()
end

##対応を考える
latestDM=''
begin
	if (messages!=nil) then
		#JSON.parse(messages.body).reverse_each do |message|
		JSON.parse(messages.body).each do |message|
			next if(message==nil)
			latestDM=message['id'] if(latestDM=='') #eachなので一番最初のが最新のtweet
			count +=1
			logdata.recvDM(message['id'],message['created_at'],message['sender']['screen_name'],message['text'])
			result = talk.parse('DM',message['sender']['screen_name'],message['text'])
			if (result['message']!=nil  and result['message']!='') then
				#命令を実行
				order(twitter,result['order'],message['sender']['screen_name'],message['id']) if(result['order']!='')
				tweet = "D #{result['to']} #{result['message']}"
				puts "\t -- update #{tweet}"
				if (twitter.update(tweet)) then
					#投稿ログに記録
					logdata.sendDM(massage['sender']['screen_name'],tweet)
					now_error_count=0
				else
					now_error_count +=1
				end
			end
		end
	end
rescue JSON::ParserError
	time = Time.now.strftime("%Y/%m/%d %H:%M:%S")
	puts "#{time}\t[Error:DM] cannot parse json"
end
logdata.latest_DM(latestDM) if(latestDM!=nil  and latestDM!='')
puts "---- All #{count} messages  ----\n\n"

#自分から話しかける
tweet = talk.think_tweet
if (tweet['message']!='') then 
	if (twitter.update(tweet['message'])) then
		logdata.sendTW('All',tweet['message'])
		now_error_count=0
	else
		now_error_count +=1
	end
end

#POSTエラー記録
if (now_error_count > 3) then
	logdata.update_dataset("status","post_error")
	logdata.update_dataset("error_start",Time.now.strftime("%Y/%m/%d %H:%M:%S"))
	puts "POST ERROR"
end

logdata.update_dataset("post_error","#{now_error_count}")
logdata.close

